package top.kangyaocoding.ecommerce.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import top.kangyaocoding.ecommerce.constants.Constants;

import java.util.Date;

/**
 * 描述: JWT工具类
 *
 * @author K·Herbert
 * @since 2025-02-17 上午10:51
 */
@Component
public class JwtUtil {

    // 密钥，从配置文件中读取
    private final String JWT_SECRET_KEY;

    // 构造函数注入 JWT_SECRET_KEY
    public JwtUtil(@Value("${data.jwt.secret}") String jwtSecretKey) {
        this.JWT_SECRET_KEY = jwtSecretKey;
    }

    // Token过期时间 24h
    private static final long JWT_EXPIRATION_TIME = Constants.JWT_EXPIRATION_TIME;

    /**
     * 生成JWT Token
     *
     * @param email 用户email
     * @return 生成的Token
     */
    public String generateToken(Long id, String email, String role) {
        Date now = new Date();
        Date expiryDate = new Date(now.getTime() + JWT_EXPIRATION_TIME);

        return JWT.create()
                .withClaim("userId", id)
                .withSubject(email)
                .withClaim("role", role)
                .withIssuedAt(now)
                .withExpiresAt(expiryDate)
                .sign(Algorithm.HMAC512(JWT_SECRET_KEY));
    }

    /**
     * 验证Token是否正确且未过期
     *
     * @param token JWT Token
     * @return 是否有效
     */
    public boolean validateToken(String token) {
        try {
            JWTVerifier verifier = JWT.require(Algorithm.HMAC512(JWT_SECRET_KEY)).build();
            verifier.verify(token);
            return true;
        } catch (JWTVerificationException exception) {
            return false;
        }
    }

    /**
     * 从Token中获取用户 id
     *
     * @param token JWT Token
     * @return id
     */
    public Long getUserIdFromToken(String token) {
        DecodedJWT jwt = JWT.decode(token);
        return jwt.getClaim("userId").asLong();
    }

    /**
     * 从Token中获取email
     *
     * @param token JWT Token
     * @return email
     */
    public String getEmailFromToken(String token) {
        DecodedJWT jwt = JWT.decode(token);
        return jwt.getSubject();
    }

    /**
     * 从Token中获取role
     *
     * @param token JWT Token
     * @return role
     */
    public String getRoleFromToken(String token) {
        DecodedJWT jwt = JWT.decode(token);
        return jwt.getClaim("role").asString();
    }

    /**
     * 检查Token是否过期
     *
     * @param token JWT Token
     * @return 是否过期
     */
    public boolean isTokenExpired(String token) {
        DecodedJWT jwt = JWT.decode(token);
        return jwt.getExpiresAt().before(new Date());
    }

}
